package com.example.core.convert.model;


import lombok.Data;
import org.hibernate.collection.internal.PersistentBag;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Collection;

@Data
public class ModelConvertor_ModelListToString implements ModelConvertor {
    private String sPropertyName;
    private String tPropertyName;

    public ModelConvertor_ModelListToString(String sPropertyName, String tPropertyName) {
        this.sPropertyName = sPropertyName;
        this.tPropertyName = tPropertyName;
    }

    /***
     *
     * val在这那个模式List
     * @param form
     * @param val
     */
    @Override
    public void convertor(Object form, Object val) throws Exception {
        if (val instanceof PersistentBag && !((PersistentBag) val).isEmpty()) {
            String[] properties = this.tPropertyName.split(PREF);
            String[] targetValues = new String[properties.length];
            if (val != null && val instanceof Collection) {
                Collection objs = (Collection) val;
                for (Object obj : objs) {
                    for (int i = 0; i < properties.length; i++) {
                        String property = properties[i];
                        Field field = ReflectionUtils.findField(obj.getClass(), property);
                        field.setAccessible(true);
                        if (targetValues[i] == null) {
                            targetValues[i] = field.get(obj).toString();
                        } else {
                            targetValues[i] = targetValues[i] + PATH + field.get(obj);
                        }
                    }
                }
            }
            if (this.tPropertyName.contains(PREF)) {
                String[] targetProperties = this.sPropertyName.split(PREF);
                if (targetProperties.length > 0) {
                    for (int i = 0; i < targetProperties.length; i++) {
                        String targetProperty = targetProperties[i];
                        Field field = ReflectionUtils.findField(form.getClass(), targetProperty);
                        field.setAccessible(true);
                        field.set(form, targetValues[i]);
                    }
                }
            }
        }
    }
}
